﻿using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
using System;

/// <summary>
/// 公共库插件的管理，管理从SSC SDK(OC||Java)发过来的全部回调，及对部分接口作了二次封装(说见接口说明).
/// 使用方法: 
/// 需在项目启动Loading Scene上添加空的GameObecjt,并添加PluginManager脚本组件，以完成必须的初始化工作。
/// </summary>
public class PluginManager : MonoBehaviour {
	/// <summary>
	/// 网络可用
	/// </summary>
	public static bool netAvailable {
		get {
			return Application.internetReachability != NetworkReachability.NotReachable;
		}
	}
	/// <summary>
	/// 是否是无线
	/// </summary>
	public static bool isWifi {
		get {
			return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork;
		}
	}

	//banner广告在哪个buildIndex场景中开始显示,
	public int showBannerSceneIdx = 1;
	string keyForAdRemovedByIAP = "IsAdRemovedByIAP";
	private bool m_isAdRemovedByIAP;
	/// <summary>
	/// 广告是否被IAP解锁了。。需要项目程序在相关IAP成功后设置.设置后，会自动用PlayerPrefs持久化，只需要在购买成功后设置一次即可.
	/// </summary>
	public bool IsAdRemovedByIAP{
		set{
			if (value) {
				m_isAdRemovedByIAP = value;
				PlayerPrefs.SetInt (keyForAdRemovedByIAP, 1);
				PlayerPrefs.Save ();
				RemoveAllAds ();
			}
		}
		get{
			return m_isAdRemovedByIAP;
		}
	}

	private static PluginManager m_instance;
	/// <summary>
	/// PluginManager实例.
	/// </summary>
	public static PluginManager Instance{
		get{
			if(m_instance==null){
				GameObject go = new GameObject("[PluginManager]");
				return go.AddComponent<PluginManager>();
			}
			return m_instance;
		}
	}

	void Awake(){
		if (m_instance)
		{
			Destroy(this.gameObject);
			return;
		}
		name = "[PluginManager]";
		m_instance = this;
		DontDestroyOnLoad(gameObject);
		m_isAdRemovedByIAP = PlayerPrefs.GetInt (keyForAdRemovedByIAP, 0) > 0;
		if (!IsAdRemovedByIAP) {
			StartCoroutine ("CheckIfBannerCanShow");
		}
		if(Application.platform== RuntimePlatform.Android || Application.platform== RuntimePlatform.IPhonePlayer){
			InternalSDKManagerScript instaneInternal = internalSDk;//init internal sdk
		}
	}

	void NotifyUnityIsReady(){
		#if UNITY_ANDROID
		try{
			if(m_adsPlugin==null) {
				m_adsPlugin = new AdsManagerScript();
				m_adsPlugin.SetGameObjectName(gameObject.name);
			}
			AndroidJavaClass jc = new AndroidJavaClass("com.common.android.LaunchActivity"); 
			AndroidJavaObject _javaObj = jc.GetStatic<AndroidJavaObject>("actInstance");
			_javaObj.Call("unityIsReady");
		}catch(Exception ex){
			Debug.Log ("Something is wrong while atempt to notify unity is ready ");
		}
		#elif UNITY_IOS
		adsPlugin.UnityIsReady();
		#endif

	}

	/// <summary>
	/// check if launch loading is over..if so, show banner if not removed by iap
	/// </summary>
	IEnumerator CheckIfBannerCanShow(){
		if (IsAdRemovedByIAP) {
			yield return null;
		}
		while (SceneManager.GetActiveScene ().buildIndex <showBannerSceneIdx) {
			yield return new WaitForSeconds(0.5f);
		}
		adsPlugin.ShowAd ((int)AdType.AdTypeBannerAds);
	}


	#region moregame
	private MoreGameManagerScript m_moreGamePage;
	/// <summary>
	/// MoreGame插件实例.
	/// </summary>
	public MoreGameManagerScript moreGame{
		get{
			if(m_moreGamePage==null){
				m_moreGamePage = new MoreGameManagerScript();
			}
			return m_moreGamePage;
		}
	}
	#endregion

	#region newblast
	private bool m_newsblastIsShow = false;
	/// <summary>
	/// 返回NewsBlast弹窗是否正在显示
	/// </summary>
	public bool newsblastIsShow{
		get { return m_newsblastIsShow; }
	}
	private NewsBlastScript m_newsBlast;
	/// <summary>
	/// Newsblast实例.
	/// </summary>
	public NewsBlastScript newsBlast{
		get{
			if(m_newsBlast==null){
				m_newsBlast = new NewsBlastScript();
				m_newsBlast.SetGameObjectNameForNB(gameObject.name);
			}
			return m_newsBlast;
		}
	}
	//下面是回调
	void NBViewDidShow(){
		m_newsblastIsShow = true;
	}
	void NBViewDidNotShow(){
		m_newsblastIsShow = false;
	}
	void NBViewDidClickCancel(){
		m_newsblastIsShow = false;
	}
	void viewDidClickOK(){
		m_newsblastIsShow = false;
	}
	#endregion


	#region rateus
	private bool m_isShowRate ;
	/// <summary>
	/// 返回当前是否有Rate Us弹框在显示
	/// </summary>
	public bool isShowRate{
		get{ return m_isShowRate; }
	}
	private RateToolScript m_rateTool;
	/// <summary>
	/// RateUs插件实例
	/// </summary>
	public RateToolScript rateTool{
		get{
			if(m_rateTool==null) {
				m_rateTool = new RateToolScript();
				m_rateTool.SetGameObjectNameForRT(gameObject.name);
			}
			return m_rateTool;
		}
	}

	/// <summary>
	/// 跳转到App Store评论.
	/// </summary>
	public void RateUs(){
		PluginManager.Instance.internalSDk.rateUs();
	}
	/// <summary>
	/// 返回是否已经评论过.
	/// </summary>
	public bool HasRated(){
		return rateTool.HasRated();
	}

	void willShowStoreProductViewController(){
		m_isShowRate = true;
	}
	void dismissedStoreProductViewController(){
		m_isShowRate = false;
	}
	#endregion

	#region 常用系统原生功能封装类(如popAlert)
	private Action<string> _OnNetworkSuccess = null;
	//native send
	void OnNetworkIsReady(string message){
		if(_OnNetworkSuccess!=null) {
			_OnNetworkSuccess(message);
			_OnNetworkSuccess = null;
		}
	}

	public void AddNetworkCheckCallBack(Action<string> onNetworkIsReady)
	{
		#if UNITY_EDITOR
		if(onNetworkIsReady!=null) onNetworkIsReady("");
		#else
		_OnNetworkSuccess = onNetworkIsReady;
		NotifyUnityIsReady ();
		#endif
	}



	private InternalSDKManagerScript m_internalSDk;
	public InternalSDKManagerScript internalSDk{
		get{
			if(m_internalSDk==null) {
				m_internalSDk = new InternalSDKManagerScript();
				m_internalSDk.setGameObjectNameForInternal(gameObject.name);
			}
			return m_internalSDk;
		}
	}
	#endregion

	#region  广告
	[System.Serializable]
	class AdClass{
		public int ad_type=-1;
		public string error_msg=null ;
	}
	[System.Serializable]
	class RewardClass{
		public string item_name=null;
		public int amount=0;
		public int isskipped=0;
	}

	private AdsManagerScript m_adsPlugin;
	/// <summary>
	/// 广告插件实例
	/// </summary>
	/// <value>The ads plugin.</value>
	public AdsManagerScript adsPlugin{
		get{
			if(m_adsPlugin==null) {
				m_adsPlugin = new AdsManagerScript();
				m_adsPlugin.SetGameObjectName(gameObject.name);
			}
			return m_adsPlugin;
		}
	}

	/// <summary>
	/// 广告加载成功回调
	/// </summary>
//	public event Action<AdType> OnAdsLoadedHandler;
	/// <summary>
	/// 广告加载失败回调
	/// </summary>
//	public event Action<AdType> OnAdsFailedHandler;
	/// <summary>
	/// 广告显示回调
	/// </summary>
	public event Action<AdType> OnAdsShowHandler;
	/// <summary>
	/// 广告关闭回调
	/// </summary>
	public event Action<AdType> OnAdsRemoveHandler;
	/// <summary>
	/// 广告将要关闭时
	/// </summary>
	public event Action<AdType> OnAdsWillRemoveHandler;
	/// <summary>
	/// 视频广告结果返回回调事件
	/// </summary>
	public event Action<string,int,bool> OnAdsRewardHandler;
	/// <summary>
	/// 视频广告结果返回回调
	/// </summary>
	public Action<string,int,bool> OnAdsRewardAction;
	/// <summary>
	/// 直接通过全屏广告奖励，返回true表示
	/// </summary>
	public Action<bool> OnInterstitialRewardAction;
	/// <summary>
	/// 广告显示超时
	/// </summary>
	public event Action<AdType> OnAdsShowTimeoutHandler;

	private Dictionary<AdType,bool> m_adsShowedKV = new Dictionary<AdType, bool>();

	private Coroutine m_TestShowInterstitial;

	enum RequestRewardAdStatus
	{
		RequestRewardAdStatusNone,
		RequestRewardAdStatusRewarding,
		RequestRewardAdStatusCrossing,
		RequestRewardAdStatusFailed,
		RequestInterstitialReward
	};
	private RequestRewardAdStatus _requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusNone;
	private bool _isCanRequestingReward = true;//是否可以请求Rewards广告

	/// <summary>
	/// 请求显示视频广告，如果此时视频广告未加载完成，就显示全屏广告代替。如果没有设置CallBack参数，则需要侦听OnAdsRewardAction
	/// 注意此处返回True时，不能保证视频广告能显示出来
	/// </summary>
	/// <returns><c>true</c>, if reward ad or show cross if reward not ready was shown, <c>false</c> otherwise.</returns>
	/// <param name="callBack">Call back.</param>
	public bool ShowRewardAdOrShowCrossIfRewardNotReady(Action<string,int,bool> callBack = null ){
		
		if(_isCanRequestingReward==false) return false;
		Invoke("RequestRewardBlock",1f);
		_isCanRequestingReward = false;

		if(!PluginManager.netAvailable){
			internalSDk.popAlertDialog ("Unlocking requires an internet connection yet it seems like you are not connected to the internet. Please check your settings or try again later.");
			return false;
		}

		if(callBack!=null) {
			OnAdsRewardAction = callBack;
		}


		if(adsPlugin.ShowAd ((int)AdType.AdTypeRewardedAds)){
			_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusRewarding;
			print("PluginManager>>RequestRewardAdStatusRewarding:"+_requestingRewardAdStatus);
			return true;
		}
		if(adsPlugin.ShowAd ((int)AdType.AdTypeInterstitialAds)){
			_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusCrossing;
			print("PluginManager>>RequestRewardAdStatusCrossing:"+_requestingRewardAdStatus);
			return true;
		}
		internalSDk.popAlertDialog ("Ads loading has problem, please try again later.");

		return false;
	}
	private void RequestRewardBlock(){
		_isCanRequestingReward = true;
	}

	/// <summary>
	/// 直接通过全屏广告解锁，如果没有设置callBack参数，则需要侦听OnInterstitialRewardAction
	/// </summary>
	/// <param name="callBack">Call back.</param>
	public void ShowInterstitialRewardAd(Action<bool> callBack = null){
		if(_isCanRequestingReward==false) return;
		Invoke("RequestRewardBlock",1f);
		_isCanRequestingReward = false;

		if(!PluginManager.netAvailable){
			internalSDk.popAlertDialog ("Unlocking requires an internet connection yet it seems like you are not connected to the internet. Please check your settings or try again later.");
			try{
				if(callBack!=null) callBack(false);
			}catch(System.Exception e){
				print("PluginManager>>ShowInterstitialRewardAd 处理有异常:"+e.Message);
			}
			return;
		}

		if(callBack!=null) {
			OnInterstitialRewardAction = callBack;
		}
		_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusNone;

		if(adsPlugin.ShowAd ((int)AdType.AdTypeInterstitialAds)){
			_requestingRewardAdStatus = RequestRewardAdStatus.RequestInterstitialReward;
			return;
		}
		if(m_TestShowInterstitial!=null) {
			StopCoroutine(m_TestShowInterstitial);
			internalSDk.removeLoadingView();
		}
		m_TestShowInterstitial = StartCoroutine(TestShowInterstitialRewardAd());
	}
	IEnumerator TestShowInterstitialRewardAd(){
		internalSDk.showLoadingView();
		for(int i = 0 ; i<5 ; ++i){
			yield return new WaitForSeconds(1f);

			if(adsPlugin.ShowAd ((int)AdType.AdTypeInterstitialAds)){
				_requestingRewardAdStatus = RequestRewardAdStatus.RequestInterstitialReward;
				internalSDk.removeLoadingView();
				if(m_TestShowInterstitial!=null) StopCoroutine(m_TestShowInterstitial);
				m_TestShowInterstitial = null;
				yield break;
			}
		}
		internalSDk.removeLoadingView();
		internalSDk.popAlertDialog ("Ads loading has problem, please try again later.");
		try{
			if(OnInterstitialRewardAction!=null) OnInterstitialRewardAction(false);
		}catch(System.Exception e){
			print("PluginManager>>TestShowInterstitialRewardAd 处理有异常:"+e.Message);
		}
		m_TestShowInterstitial = null;
	}


	/// <summary>
	/// 判断全屏广告是否显示
	/// </summary>
	/// <returns><c>true</c>, if screen ad is showed was checked, <c>false</c> otherwise.</returns>
	public bool CheckScreenAdIsShowed(){
		foreach (AdType ad in m_adsShowedKV.Keys) {
			if (ad != AdType.AdTypeBannerAds && m_adsShowedKV [ad] == true) {
				return true;
			}
		}
		return false;
	}

	/// <summary>
	/// 判断广告是否已经显示
	/// </summary>
	/// <returns><c>true</c>, if ad is showed was checked, <c>false</c> otherwise.</returns>
	/// <param name="type">Type.</param>
	public bool CheckAdIsShowed(AdType type){
		if(m_adsShowedKV.ContainsKey(type) && m_adsShowedKV[type]) return true;
		return false;
	}
	//ads回调
	void OnAdsLoaded (string message){
		Debug.Log ("PluginManager>>OnAdsLoaded: " + message);
//		AdType adType = (AdType)(JsonUtility.FromJson<AdClass>(message).ad_type);
//		try{
//			if(OnAdsLoadedHandler!=null) OnAdsLoadedHandler.Invoke(adType);
//		}catch(System.Exception e){
//			print("PluginManager>>OnAdsLoadedHandler 处理有异常:"+e.Message);
//		}
	}
	void OnAdsFailed (string message){
		Debug.Log ("PluginManager>>OnAdsFailed: " + message + "   curr_status:"+_requestingRewardAdStatus);
		AdClass adClass = JsonUtility.FromJson<AdClass>(message);
		AdType adType = (AdType)adClass.ad_type;

		if(!String.IsNullOrEmpty(adClass.error_msg)){
			//视频广告显示超时
			if ( adClass.error_msg == "VIDEO_PLAYBACK_ERROR" && adType == AdType.AdTypeRewardedAds) {
				print("PluginManager>>Ad Timeout: VIDEO_PLAYBACK_ERROR");

				_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusFailed;
				AudioListener.pause = false;
				m_adsShowedKV[adType] = false;
				if(adsPlugin.ShowAd ((int)AdType.AdTypeInterstitialAds)){
					_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusCrossing;
				}else{
					internalSDk.popAlertDialog ("Ads loading has problem, please try again later.");
				}

				try{
					if(OnAdsShowTimeoutHandler!=null) OnAdsShowTimeoutHandler.Invoke(adType);
				}catch(System.Exception e){
					print("PluginManager>>OnAdsShowTimeoutHandler 处理有异常:"+e.Message);
				}
			}
			//全屏广告显示超时
			else if ( adClass.error_msg == "INTERSTITIAL_SHOWING_ERROR" && adType == AdType.AdTypeInterstitialAds) {
				print("PluginManager>>Ad Timeout: INTERSTITIAL_SHOWING_ERROR");

				if(_requestingRewardAdStatus == RequestRewardAdStatus.RequestRewardAdStatusCrossing 
					|| _requestingRewardAdStatus == RequestRewardAdStatus.RequestInterstitialReward)
				{
					internalSDk.popAlertDialog ("Ads loading has problem, please try again later.");
				}
				_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusFailed;
				AudioListener.pause = false;
				m_adsShowedKV[adType] = false;

				try{
					if(OnAdsShowTimeoutHandler!=null) OnAdsShowTimeoutHandler.Invoke(adType);
				}catch(System.Exception e){
					print("PluginManager>>OnAdsShowTimeoutHandler 处理有异常:"+e.Message);
				}
			}
		}

//		try{
//			if(OnAdsFailedHandler!=null) OnAdsFailedHandler.Invoke(adType);
//		}catch(System.Exception e){
//			print("PluginManager>>OnAdsFailedHandler 处理有异常:"+e.Message);
//		}
	}
	void OnAdsWillCollapse (string message){
		Debug.Log ("PluginManager>>OnAdsWillCollapse: " + message);
		AdType adType = (AdType)(JsonUtility.FromJson<AdClass>(message).ad_type);
		try{
			if(OnAdsWillRemoveHandler!=null) OnAdsWillRemoveHandler.Invoke(adType);
		}catch(System.Exception e){
			print("PluginManager>>OnAdsWillRemoveHandler 处理有异常:"+e.Message);
		}
	}
	void OnAdsCollapsed (string message){
		Debug.Log ("PluginManager>>OnAdsCollapsed: " + message);
		AdType adType = (AdType)(JsonUtility.FromJson<AdClass>(message).ad_type);
		m_adsShowedKV[adType] = false;
		if (adType == AdType.AdTypeInterstitialAds) {
			internalSDk.removeLoadingView();
			if(_requestingRewardAdStatus == RequestRewardAdStatus.RequestRewardAdStatusCrossing){
				try{
					if(OnAdsRewardAction!=null) OnAdsRewardAction("RewardCross", 1, false);
					if(OnAdsRewardHandler!=null) OnAdsRewardHandler.Invoke("RewardCross", 1, false);
				}catch(System.Exception e){
					print("PluginManager>>OnAdsRewardHandler 处理中有异常:"+e.Message);
				}
			}
			else if(_requestingRewardAdStatus == RequestRewardAdStatus.RequestInterstitialReward)
			{
				try{
					if(OnInterstitialRewardAction!=null) OnInterstitialRewardAction(true);
				}catch(System.Exception e){
					print("PluginManager>>OnAdsRewardHandler 处理中有异常:"+e.Message);
				}
			}
			_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusNone;
		}
		if(adType == AdType.AdTypeRewardedAds || adType == AdType.AdTypeInterstitialAds){
			AudioListener.pause = false;
			_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusNone;
		}
		#if UNITY_ANDROID
		try{
			if(OnAdsWillRemoveHandler!=null) OnAdsWillRemoveHandler.Invoke(adType);
		}catch(System.Exception e){
			print("PluginManager>>OnAdsWillRemoveHandler 处理有异常:"+e.Message);
		}
		#endif
		try{
			if(OnAdsRemoveHandler!=null) OnAdsRemoveHandler.Invoke(adType);
		}catch(System.Exception e){
			print("PluginManager>>OnAdsRemoveHandler 处理有异常:"+e.Message);
		}
	}
	void OnAdsExpanded (string message){
		AdType adType = (AdType)(JsonUtility.FromJson<AdClass>(message).ad_type);
		if( adType == AdType.AdTypeRewardedAds || adType == AdType.AdTypeInterstitialAds) {
			if(m_TestShowInterstitial!=null) {
				StopCoroutine(m_TestShowInterstitial);
				m_TestShowInterstitial = null;
			}
			if (!m_adsShowedKV.ContainsKey(adType) || m_adsShowedKV[adType] == false )
			{
				AudioListener.pause = true;
			}
		}
		m_adsShowedKV[adType] = true;
		try{
			if(OnAdsShowHandler!=null) OnAdsShowHandler.Invoke(adType);
		}catch(System.Exception e){
			print("PluginManager>>OnAdsShowHandler 处理有异常:"+e.Message);
		}
	}
	void OnAdsClicked(string message){

	}
	void OnRewarded (string message){
		_requestingRewardAdStatus = RequestRewardAdStatus.RequestRewardAdStatusNone;

		RewardClass rewards = JsonUtility.FromJson<RewardClass>(message);
		print("PluginManager>>OnRewards:"+message);
		try{
			if(OnAdsRewardAction!=null) OnAdsRewardAction(rewards.item_name,rewards.amount,rewards.isskipped>0);
			if(OnAdsRewardHandler!=null) OnAdsRewardHandler.Invoke(rewards.item_name,rewards.amount,rewards.isskipped>0);
		}catch(System.Exception e){
			print("PluginManager>>OnAdsRewardHandler 处理中有异常:"+e.Message);
		}
	}

	/// <summary>
	/// 移除所有广告
	/// </summary>
	public void RemoveAllAds(){
		adsPlugin.RemoveAd((int)AdType.AdTypeBannerAds);
		//adsPlugin.RemoveAd((int)AdType.AdTypeCrosspromoAds);
		adsPlugin.RemoveAd((int)AdType.AdTypeInterstitialAds);
		adsPlugin.RemoveAd((int)AdType.AdTypeNativeAds);
		//adsPlugin.RemoveAd((int)AdType.AdTypeRectAds);
		adsPlugin.RemoveAd((int)AdType.AdTypeRewardedAds);
		//adsPlugin.SetHidden((int)AdType.AdTypeBannerAds,true);
	}
	#endregion


	#region iap处理

	private bool m_isIap ;
	/// <summary>
	/// 是否正在处理IAP购买(比如你希望从enter foreground的时候，如果正在处理iap，可不显示广告，可用此状态变量判断)
	/// </summary>
	public bool isIap{
		get{ return m_isIap; }
	}

	private IAPScript m_iapPlugin;
	/// <summary>
	/// IAP插件实例
	/// </summary>
	private IAPScript iapPlugin{
		get{
			if(m_iapPlugin==null) {
				m_iapPlugin = new IAPScript();
				m_iapPlugin.SetGameObjectNameForIAP(gameObject.name);
			}
			return m_iapPlugin;
		}
	}

	/// <summary>
	/// IAP Restore 成功回调, 参数为字符串数组
	/// </summary>
	public event Action<string[]> OnRestoreQuerySuccessEvent;

	/// <summary>
	/// IAP 购买成功回调.
	/// </summary>
	public event Action<string> OnRestoreSuccessEvent;
	/// <summary>
	/// IAP 购买成功回调.
	/// </summary>
	public event Action<string> OnPurchaseSuccessEvent;

	/// <summary>
	/// IAP购买开始事件,如可用于播放IAP购买loading动画.
	/// </summary>
	public event Action OnStartIapEvent;

	/// <summary>
	/// IAP处理结束事件,如可用于结束IAP购买loading动画.
	/// </summary>
	public event Action OnEndIapEvent;

	//	[System.Obsolete("不需要自己处理，已在PluginManager中处理")]
	//	public event Action<String> OnPurchaseFailedEvent;
	//	[System.Obsolete("不需要自己处理，已在PluginManager中处理")]
	//	public event Action<String> OnRestoreFailedEvent;
	//	[System.Obsolete("不需要自己处理，已在PluginManager中处理")]
	//	public event Action<String> OnPurchaseCancelledEvent;
	//	[System.Obsolete("不需要自己处理，已在PluginManager中处理")]
	//	public event Action OnProductsNotReadyEvent;


	[System.Serializable]
	class IapClass{
		public string product_id=null;
	}
	[System.Serializable]
	class RestoreClass{
		public List<string> product_ids=null;
	}
	[System.Serializable]
	class IapFailClass{
		public string product_id=null;
		public int response_index = 0;
	}

	/// <summary>
	/// 购买一个
	/// </summary>
	/// <param name="productId">Product identifier.</param>
	/// <param name="skuType">Sku type.</param>
	public void PurchaseById(string productId,SkuType skuType = SkuType.Managed)
	{
		if(IsPurchased(productId)){
			internalSDk.popAlertDialog("You've already purchased this item.");
			if(OnPurchaseSuccessEvent!=null) OnPurchaseSuccessEvent.Invoke(productId);
			return;
		}
		if(!PluginManager.netAvailable){
			internalSDk.popAlertDialog("Please connect to internet and try again!");
			return;
		}
		iapPlugin.PurchaseById(productId,skuType);
	}
	/// <summary>
	/// Restore 一个
	/// </summary>
	/// <param name="productId">Product identifier.</param>
	public void RestorePurchaseById(string productId)
	{
		if(!PluginManager.netAvailable){
			internalSDk.popAlertDialog("Please connect to internet and try again!");
			return;
		}
		iapPlugin.RestorePurchaseById(productId);
	}
	/// <summary>
	/// Restore 所有
	/// </summary>
	public void RestoreAllPurchases()
	{
		if(!PluginManager.netAvailable){
			internalSDk.popAlertDialog("Please connect to internet and try again!");
			return;
		}
		iapPlugin.RestoreAllPurchases();
	}

	/// <summary>
	/// 是否购买了非消耗性iap
	/// </summary>
	/// <returns><c>true</c> if this instance is purchased the specified iapId; otherwise, <c>false</c>.</returns>
	/// <param name="iapId">Iap identifier.</param>
	public bool IsPurchased(string iapId){
		return PlayerPrefs.GetInt("Iap_"+iapId,0)==1;
	}

	//iap回调
	void OnPurchaseSuccess(string message){
		string iapId = JsonUtility.FromJson<IapClass>(message).product_id;
		PlayerPrefs.SetInt("Iap_"+iapId,1);
		PlayerPrefs.Save();
		#if  UNITY_IOS
		internalSDk.popAlertDialog("Thank you for your purchase.");
		#endif
		if(OnPurchaseSuccessEvent!=null) OnPurchaseSuccessEvent.Invoke(iapId);
	}
	void OnPurchaseFailed(string message){
		#if  UNITY_IOS
		internalSDk.popAlertDialog("Purchase failed.");
		#elif UNITY_ANDROID

		if (Application.platform == RuntimePlatform.Android) {

			int platformCode = AndroidHelper.getIapManagerAndroidObject ().GetStatic<int>("platformCode");
			if(platformCode==32){

				IapFailClass fail = JsonUtility.FromJson<IapFailClass>(message);
				string iapId = fail.product_id;
				int code = fail.response_index;

				if(code==7){
					internalSDk.popAlertDialog("You've already purchased this item.");

					PlayerPrefs.SetInt("Iap_"+iapId,1);
					PlayerPrefs.Save();

					if(OnPurchaseSuccessEvent!=null) OnPurchaseSuccessEvent.Invoke(iapId);

				}else{
					internalSDk.popAlertDialog("Purchase failed.");
				}
			}
		}
		#endif

	}
	void OnPurchaseCancelled(string message){
		#if  UNITY_IOS
		internalSDk.popAlertDialog("Your purchase was canceled. No purchase was made and your account was not charged.");
		#endif
	}
	void OnRestoreFailed(string message){
		#if  UNITY_IOS
		internalSDk.popAlertDialog("We have detected a problem restoring your purchases. No purchases were restored. Please check your device settings and storage and try again later..");
		#endif
	}             
	void OnRestoreQuerySuccess(string message){
		if(string.IsNullOrEmpty(message)){
			if(OnRestoreQuerySuccessEvent!=null) OnRestoreQuerySuccessEvent.Invoke(null);
			internalSDk.popAlertDialog ("We could not find any previous purchases. No purchases were restored.");
		}else{
			internalSDk.popAlertDialog("Restore successfully!");
			RestoreClass iapArray = JsonUtility.FromJson<RestoreClass>(message);
			if(iapArray !=null && iapArray.product_ids!=null){
				foreach(string iapId in iapArray.product_ids){
					PlayerPrefs.SetInt("Iap_"+iapId,1);
					PlayerPrefs.Save();
				}
			}
			if(OnRestoreQuerySuccessEvent!=null) 
				OnRestoreQuerySuccessEvent.Invoke(iapArray.product_ids.ToArray());
		}
	}
	void OnRestoreSuccess(string message){
		internalSDk.popAlertDialog ("Restore successfully!");
		string iapId = JsonUtility.FromJson<IapClass>(message).product_id;
		PlayerPrefs.SetInt("Iap_"+iapId,1);
		PlayerPrefs.Save();
		if(OnRestoreSuccessEvent!=null) OnRestoreSuccessEvent.Invoke(iapId);
	}
	void OnRestoreCancelled(string message){

	}
	void OnNoRestore(string message){
		internalSDk.popAlertDialog ("No purchases were restored.");
	}
	void OnProductRequestBegin(string message){
		if(OnStartIapEvent!=null) OnStartIapEvent();
		CancelInvoke("StopIap");
		m_isIap = true;
	}
	void OnProductRequestEnd(string message){
		if(OnEndIapEvent!=null) OnEndIapEvent.Invoke();
		Invoke("StopIap",0.75f);//延迟一段时间
	}
	void StopIap(){
		m_isIap = false;
	}
	void OnProductsNotReady(string message){
		#if  UNITY_IOS
		internalSDk.popAlertDialog("Purchase not ready.");
		#endif
	}
	#endregion

	#region share
	/// <summary>
	/// 图片保存成功回调
	/// </summary>
	public event Action OnImageSaveSuccessed;
	/// <summary>
	/// 图片保存失败回调
	/// </summary>
	public event Action OnImageSaveFailed;
	/// <summary>
	/// 分享成功回调()
	/// </summary>
	public event Action OnShareDidSuccessed;
	/// <summary>
	/// 分享失败回调
	/// </summary>
	public event Action OnShareDidFailed;

	private ShareControllerScript m_sharePlugin;
	/// <summary>
	/// 分享插件实例(保存图片，发送邮件，分享twitter等)
	/// </summary>
	public ShareControllerScript sharePlugin{
		get{
			if(m_sharePlugin==null) {
				m_sharePlugin = new ShareControllerScript();
				m_sharePlugin.SetGameObjectNameForShare(gameObject.name);
			}
			return m_sharePlugin;
		}
	}

	void OnShareSuccessed(string message){
		if(OnShareDidSuccessed!=null) OnShareDidSuccessed.Invoke();
	}

	void OnShareFailed(string message){
		if(OnShareDidFailed!=null) OnShareDidFailed.Invoke();
	}

	void OnSaveImageSuccessed(string message){
		if(OnImageSaveSuccessed!=null) OnImageSaveSuccessed.Invoke();
	}

	void OnSaveImageFailed(string message){
		if(OnImageSaveFailed!=null) OnImageSaveFailed.Invoke();
	}
	#endregion


	#region Analytics
	private AnalyticsSDKScript m_analyticsPlugin;
	/// <summary>
	/// 统计插件实例
	/// </summary>
	public AnalyticsSDKScript analyticsPlugin{
		get{
			if(m_analyticsPlugin==null) {
				m_analyticsPlugin = new AnalyticsSDKScript();
			}
			return m_analyticsPlugin;
		}
	}

	#endregion


	#region Permissions Android保存图片权限
	/// <summary>
	/// 保存图片权限申请结果回调.(Android用，IOS调用申请权限，SDK都是啥也没做，直接返回申请成功)
	/// </summary>
	public System.Action<bool,string> OnPermissionAction;
	/// <summary>
	/// 运行时申请权限实例(write external for android)
	/// </summary>
	private RuntimePermissionScript m_permissiom;
	public RuntimePermissionScript permissiom{
		get{
			if(m_permissiom==null) {
				m_permissiom = new RuntimePermissionScript();
				m_permissiom.setGameObjectName (gameObject.name);
			}
			return m_permissiom;
		}
	}
	/// <summary>
	/// Android申请WriteExternalStorage权限(安卓6.0以后可动态申请权限，不仅仅是在安装时)
	/// 如果你要申请特殊的权限，可以用 permissiom.requestRuntimePermissions 方法
	/// </summary>
	public void RequestPermission(){
		#if UNITY_ANDROID
		permissiom.requestRuntimePermissions(100,(long)PERMISSION.kWriteExternalStorage);
		#else
		if(OnPermissionAction!=null) OnPermissionAction.Invoke(true,"-1");
		#endif
	}

	//回调，成功
	void onPermissionGranted(string requestCode){
		if(OnPermissionAction!=null) OnPermissionAction.Invoke(true,requestCode);
	}
	//回调，失败
	void onPermissionDenied(string requestCode){
		if(OnPermissionAction!=null) OnPermissionAction.Invoke(false,requestCode);
	}
	#endregion


	#if UNITY_ANDROID
	public void QuitGame(){
		AndroidHelper.getObj ().Call ("quitGame");
	}
	#endif
}
